package com.bjsasc.open.scheduledtask;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.bjsasc.open.util.DateUtils;
import com.bjsasc.open.util.DeletDirectoryAndFiles;
import com.bjsasc.open.util.StringUtil;

/** 
 * @ClassName: KillProcessMP4Task 
 * @Description:    后台会跑一个定时任务，每间隔3分钟，从Set集合中扫描所有的转MP4进程号，判断在Redis中的String类型的进程号key是否存在 
 * @author zhangbingbing 
 * @date 2024年4月8日 下午2:09:29 
 * @version 1.0 
 */
@Component
@ConditionalOnProperty(prefix = "scheduling", name = "enabled", havingValue = "true")
public class KillProcessMP4Task {
	
	private static final Logger log = LoggerFactory.getLogger(KillProcessMP4Task.class);
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;	 
	 
	private StringUtil stringUtil;	
	
	 /**
	  *   实时流转为mp4后所在的路径
	 */
	 @Value("${mp4.path}")
	 private String MP4_PATH;
	
	private static final SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
    /**
    * @author zhangbingbing   
    * 
    *       定时清空无效的转MP4进程
    */
	@Scheduled(cron = "0 0/3 * * * ?") // 每间隔3分钟触发一次
	public void killProcessMP4() {
		log.info("killProcessMP4开始的时间是 ：{}." ,dataFormat.format(new Date()));
		try{
			Set<String> resultSet =stringRedisTemplate.opsForSet().members(stringUtil.RTSP_TO_MP4_SET);
			if(resultSet.size()>0) {
				for(String pid:resultSet) {
					log.info("进程号为: " + pid);
		    		String value = stringRedisTemplate.opsForValue().get(stringUtil.MP4_STRING + pid);
//		    		log.info("从redis中查询的结果为:" + value);
		    		if(StringUtils.isEmpty(value)) {
		    			log.info("该训练任务已结束，可以从set中清除，关闭转MP4进程");
		    			
		    			//将该进程号从Set集合中删除
		   			 	stringRedisTemplate.opsForSet().remove(stringUtil.RTSP_TO_MP4_SET, pid);
		   			 
		   			 	//将该进程从后台关闭
		   			 	String strCommand="kill -15 "+pid;
		   			 	Process process = Runtime.getRuntime().exec(strCommand);
		   			 	log.info(pid + "后台转流进程关闭");
		   			 	
		    		} 
				
				}
				
			}else {
				log.info("rtsp流转MP4文件对应的set集合里的值为空");
			}
			
		} catch (Exception ex) {
			log.error("定时清空无效的转MP4进程定时任务执行失败,原因是:" + ex.toString());
		}
		
	}	
	
    /**
    * @author zhangbingbing   
    * 
    *       定时删除流媒体服务器中MP4文件,只保留10天
    */
	@Scheduled(cron = "0 30 5 * * ?") // 每天凌晨5点30分触发一次
	public void deleteMP4File() {
		log.info("deleteMP4File开始的时间是 ：{}." ,dataFormat.format(new Date()));
		try{
			String filepath = "";
			String wjlj = DateUtils.getPreviousDayTimeStr(10,"yyyyMMdd");//前10天的日期
			
			//获取文件路径
            if(MP4_PATH.endsWith("/") || MP4_PATH.endsWith("\\")){
            	filepath = MP4_PATH + wjlj;
            }else{
            	filepath = MP4_PATH + "/" + wjlj;
            }
            
            log.info("文件路径为:{}",filepath);
            
            boolean flag =  DeletDirectoryAndFiles.deleteDirectoryOrFile(filepath);
            log.info("文件删除结果为:" + flag);
			
		} catch (Exception ex) {
			log.error("定时删除流媒体服务器中MP4文件定时任务执行失败,原因是:" + ex.toString());
		}
		
	}	
	
}
